import cv2

import core
import time
import logging
import socket

import socket_header
from count import Counter

# 初始化日志函数
logging.basicConfig(level=logging.WARNING,
                    filename='./mediapipe_log.log',
                    filemode='a',
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

ip = ("192.168.101.7", 10101)
# ip = ("127.0.0.1", 10101)

try:
    tcp_socket = socket_header.TCP_Send(*ip)
except:
    logging.error("Cannot connect targets")
    raise ConnectionError("Cannot connect targets")

try:
    tcp_socket.send_msg(core.connection, mod=0)
    tcp_socket.send_msg(core.angle, mod=1)
except:
    logging.error("fail to upload connection")
    raise ConnectionError("fail to upload connection")

try:
    c = Counter()
except:
    logging.error("Cannot load json")
    raise IOError("Cannot load json")


# 打开摄像头
cap = cv2.VideoCapture(0)
if cap.isOpened() == False:
    logging.error("fail to open camera")
    raise RuntimeError("fail to open camera")

d = 0
num = 0
landmark = []
count_mod = 0
times = 0
break_ifg = 0
print("Wait for cap")
while True:
    time.sleep(1)
    resv = tcp_socket.recv()
    print("recv ", resv)
    if resv == -1:
        continue
    if resv["start"] == 1:
        c.get_id(resv['count_id'])
        break
del resv
print("Start Cap!")
strat = time.time()
while cap.isOpened():
    try:
        resv_msg = tcp_socket.recv()
    except:
        resv_msg = -1
        pass
    if resv_msg != -1:
        c.get_id(resv_msg['count_id'])
        print("count_id=", c.id)
        if resv_msg["start"] == 2:
            print("Cap sleep")
            while True:
                resv = tcp_socket.recv()
                time.sleep(1)
                if resv == -1:
                    continue
                if resv["start"] == 1:
                    print("Cap starting")
                    c.get_id(resv['count_id'])
                    print("count_id=", c.id)
                    break
                elif resv["start"] == 0:
                    break_ifg == 1
                    break
        if resv_msg["start"] == 0:
            break_ifg == 1
        if break_ifg == 1:
            break
        times = 0
    try:
        ret, frame = cap.read()
    except:
        logging.error("fail to get frame")
        raise RuntimeError("fail to get frame")
    # if ret == False:
    #     cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
    #     continue
    # # if ret == False:
    # #     break
    d += 1
    if d % 3 == 1:
        try:
            landmark = core.detector(frame)
        except:
            logging.error("fail to get landmark")
            raise RuntimeError("fail to get landmark")
    if len(landmark) != 0:
        try:
            frame = core.draw_connections(frame, landmark)
            angle = core.draw_angle(landmark)
            once = c.count(angle)
            times += once
        except:
            logging.error("fail to draw connection")
            raise RuntimeError("fail to draw connection")
    try:
        tcp_socket.send_msg(landmark, mod=2)
    except:
        logging.error("fail to send landmarks")
        raise ConnectionError("fail to send landmarks")
    try:
        tcp_socket.send_msg(times, mod=3)
    except:
        raise ConnectionError("fail to send times")
    t = time.time()
    # cv2.putText(frame, str(int(d / (t - strat))), (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)
    # cv2.putText(frame, str(times), (10, 110), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)
    # cv2.imshow("123", frame)
    print("FPS: {:.2f}".format(d / (t - strat)))
    # if cv2.waitKey(1) & 0xff == ord("q"):
    #     break

print("Cap Release")
tcp_socket.close_socket()
# cv2.destroyAllWindows()
cap.release()
